/**
 * 通用工具函数
 */

/**
 * 格式化时间
 * @param {Date | string | number} time 时间
 * @param {string} cFormat 格式
 * @returns {string | null} 格式化后的时间字符串
 */
export function parseTime(time: Date | string | number, cFormat?: string): string | null {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date: Date
  if (typeof time === 'object') {
    date = time as Date
  } else {
    if (typeof time === 'string') {
      if (/^[0-9]+$/.test(time)) {
        // 支持 "1548221490638"
        time = parseInt(time)
      } else {
        // 支持 safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj: Record<string, number | string> = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // 注意: getDay() 在周日返回 0
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value as number] }
    return `${value}`.padStart(2, '0')
  })
  return time_str
}

/**
 * 格式化时间为相对时间
 * @param {number} time 时间戳
 * @param {string} option 格式化选项
 * @returns {string} 格式化后的字符串
 */
export function formatTime(time: number, option?: string): string {
  if ((`${time}`).length === 10) {
    time = parseInt(`${time}`) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d.getTime()) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // 少于1小时
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option) || ''
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * URL 参数转对象
 * @param {string} url URL
 * @returns {Record<string, string>} 参数对象
 */
export function param2Obj(url: string): Record<string, string> {
  const search = decodeURIComponent(url.split('?')[1] || '').replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj: Record<string, string> = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

/**
 * 从 hash 部分获取查询参数
 * @param {string} name 参数名
 * @returns {string|null} 参数值
 */
export function getQueryByNameHash(name: string): string | null {
  const hash = location.hash || ''
  const queryString = hash.split('?')[1] || ''
  return new URLSearchParams(queryString).get(name)
}

/**
 * 从 URL 获取查询参数
 * @param {string} name 参数名
 * @returns {string} 参数值
 */
export function getQueryByName(name: string): string {
  const queryList = location.href.split('?')[1]?.split('&') || []
  const curQuery = queryList.find(item => item.includes(name))
  const res = curQuery?.split('=')[1] || ''
  return res.split('#')[0]
} 